package com.xiangxiao.rpan.storage.utils;

import com.xiangxiao.rpan.utils.UUIDUtil;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @ClassName FileTransfer
 * @Auther admin
 * @Email 573768011@qq.com
 * @Date 2024/2/26 15:21
 */
public class FileTransfer {
  public static File transferMultipartToFile(MultipartFile multipartFile) {
    // 选择用缓冲区来实现这个转换即使用java 创建的临时文件使用 MultipartFile.transferto()方法 。
    File filePath = null;
    try {
      String tmpDir = System.getProperty("java.io.tmpdir");
      if (!tmpDir.endsWith("/")) {
        tmpDir = tmpDir + "/";
      }
      String originalFilename = multipartFile.getOriginalFilename();
      String prefix = originalFilename.lastIndexOf(".") != -1 ? originalFilename.substring(originalFilename.lastIndexOf(".")) : ".tmp";
      String path = UUIDUtil.getUUID().toString().replace("-", "") + prefix;
      filePath = new File(tmpDir, path);

      if (!filePath.exists()) {
        filePath.createNewFile();
      };
      multipartFile.transferTo(filePath);
      filePath.deleteOnExit();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return filePath;
  }
}
